// 借用申请页面逻辑
const apiService = require('../../../../js/services/api/sharedDatabaseService');

Page({
  data: {
    itemId: '',
    item: {},
    startDate: '',
    endDate: '',
    today: '',
    maxDate: '',
    description: ''
  },

  onLoad: function (options) {
    // 设置导航栏标题
    wx.setNavigationBarTitle({ title: '申请借用' });

    // 获取物品ID
    if (options && options.id) {
      this.setData({ itemId: options.id });
      this.loadItemDetail();
    } else {
      wx.showToast({
        title: '未找到物品信息',
        icon: 'none',
        complete: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      });
    }

    // 初始化日期
    const today = new Date();
    const maxDate = new Date();
    maxDate.setFullYear(maxDate.getFullYear() + 1); // 最大日期为1年后

    this.setData({
      today: this.formatDate(today),
      maxDate: this.formatDate(maxDate),
      startDate: this.formatDate(today)
    });
  },

  /**
   * 加载物品详情
   */
  async loadItemDetail() {
    try {
      wx.showLoading({ title: '加载中' });

      // 调用API获取物品详情
      const result = await apiService.getIdleItemDetail(this.data.itemId);

      if (!result || !result.data) {
        throw new Error('未找到物品详情');
      }

      // 设置物品信息
      this.setData({ item: result.data });

      // 设置默认结束日期（根据可借用时长）
      const defaultEndDate = new Date();
      defaultEndDate.setDate(defaultEndDate.getDate() + (result.data.borrow_duration || 3));
      this.setData({ endDate: this.formatDate(defaultEndDate) });

    } catch (error) {
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  /**
   * 格式化日期为YYYY-MM-DD
   */
  formatDate: function (date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  /**
   * 选择开始日期
   */
  onStartDateChange: function (e) {
    const startDate = e.detail.value;
    this.setData({ startDate });

    // 重置结束日期为开始日期加上可借用时长
    const endDate = new Date(startDate);
    endDate.setDate(endDate.getDate() + (this.data.item.borrow_duration || 3));
    this.setData({ endDate: this.formatDate(endDate) });
  },

  /**
   * 选择结束日期
   */
  onEndDateChange: function (e) {
    this.setData({ endDate: e.detail.value });
  },

  /**
   * 输入借用说明
   */
  onDescriptionInput: function (e) {
    this.setData({ description: e.detail.value });
  },

  /**
   * 提交申请
   */
  async submitApplication() {
    const { itemId, startDate, endDate, description } = this.data;

    // 简单验证
    if (!description) {
      return wx.showToast({ title: '请输入借用说明', icon: 'none' });
    }

    try {
      wx.showLoading({ title: '提交中' });

      // 调用API提交申请
      const result = await apiService.submitBorrowApplication({
        itemId,
        startDate,
        endDate,
        description
      });

      wx.showToast({
        title: '申请提交成功',
        icon: 'success',
        complete: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      });

    } catch (error) {
      wx.showToast({
        title: error.message || '提交失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  }
});